package controllers

import (
	"fmt"
	"math/rand"
	"net/http"
	"shop-backend/internal/config"
	models "shop-backend/internal/user/usermodels"
	"time"

	"github.com/gin-gonic/gin"
)

// 注册请求结构体
type RegisterRequest struct {
	Phone       string `json:"phone" binding:"required"`
	Password    string `json:"password" binding:"required"`
	Code        string `json:"code" binding:"required"`
	CompanyName string `json:"company_name" binding:"required"`
	ContactName string `json:"contact_name" binding:"required"`
}

type LoginRequest struct {
	Phone    string `json:"phone" binding:"required"`
	Password string `json:"password" binding:"required"`
}

// 发送验证码请求结构体
type SendCodeRequest struct {
	Phone string `json:"phone" binding:"required"`
}

// 注册接口
func Register(c *gin.Context) {
	var req RegisterRequest

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
		return
	}

	// 验证验证码（这里只做简单演示，实际应从 Redis 或数据库获取）
	if req.Code != "123456" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "验证码错误"})
		return
	}

	// 检查手机号是否已注册
	var existing models.User
	config.DB.Where("phone = ?", req.Phone).First(&existing)
	if existing.ID != 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "手机号已注册"})
		return
	}

	// 创建新用户
	user := models.User{
		Phone: req.Phone,
		//Code:        req.Code,
		Password:    req.Password,
		CompanyName: req.CompanyName,
		ContactName: req.ContactName,
	}

	if err := config.DB.Create(&user).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "注册失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "注册成功"})
}

// 发送验证码接口
func SendCode(c *gin.Context) {
	var req SendCodeRequest

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "手机号不能为空"})
		return
	}

	// 生成6位验证码（真实场景应保存到 Redis 并设置过期时间）
	code := fmt.Sprintf("%06d", rand.Intn(1000000))
	fmt.Printf("发送验证码 %s 给手机号 %s\n", code, req.Phone)

	// 这里只是演示，不真的发送短信
	c.JSON(http.StatusOK, gin.H{"message": "验证码发送成功", "code": code})
}

func init() {
	rand.Seed(time.Now().UnixNano())
}

// controllers/user_controller.go
func Login(c *gin.Context) {
	var req LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
		return
	}

	var user models.User
	if err := config.DB.Where("phone = ?", req.Phone).First(&user).Error; err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "用户不存在"})
		return
	}

	if user.Password != req.Password {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "密码错误"})
		return
	}

	// 登录成功，返回用户信息（前端可用来展示头像、联系人等）
	c.JSON(http.StatusOK, gin.H{
		"message":      "登录成功",
		"user_id":      user.ID,
		"contact_name": user.ContactName,
	})
}
